import { request } from "../../request/index";

// pages/goos_detail/index.js
Page({

    data: {
        goodsDetail:{}
    },
    GoodsInfo:{},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const {goods_id} = options;
        this.getGoodsDetail(goods_id);
    },
    async getGoodsDetail(goods_id) {
        const goodsDetail = await request({
            url:'https://api-hmugo-web.itheima.net/api/public/v1/goods/detail',
            data:{goods_id}
        });
        
        this.setData({
            goodsDetail:{
                goods_name:goodsDetail.data.message.goods_name,
                goods_price:goodsDetail.data.message.goods_price,
                goods_introduce:goodsDetail.data.message.goods_introduce.replace(/\.webp/g,'.jpg'),
                pics:goodsDetail.data.message.pics
            }
        })
        this.GoodsInfo = goodsDetail;

    },

    handlePrevewImage(e){
        const urls = this.GoodsInfo.data.message.pics.map(v=>v.pics_mid);
        const current = e.currentTarget.dataset.url
        wx.previewImage({
            current, 
            urls
            
        })
    },

    handleCartAdd(e){
        //1 获取缓存中的购物车数组
        let cart = wx.getStorageSync("cart")||[];
        //2 判断商品对象是否存在购物车数组中
        let index = cart.findIndex(v=>v.data.message.goods_id===this.GoodsInfo.data.message.goods_id);
        console.log(this.GoodsInfo);
        if(index===-1){
            this.GoodsInfo.num=1;
            this.GoodsInfo.checked=true;
            cart.push(this.GoodsInfo);
        }else{
            cart[index].num++;
        }
        wx.setStorageSync('cart', cart);
        wx.showToast({
            title: '加入成功',
            icon: 'success',
            mask: true,
        });

    }
})